<template>
  <div>
    <h2 style="margin:  auto;">审批页面</h2>
    <br>
    <el-container>
      <el-aside width="650px">
        <el-form ref="ruleFormRef" style="max-width: 600px;height: 74vh;" :model="RecordForm" :rules="rules"
          label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>
          <el-form-item label="姓名" prop="nickName">
            <el-input v-model="ruleForm.nickName" disabled />
          </el-form-item>
          <el-form-item label="部门" prop="depId">
            <el-select v-model="ruleForm.depId" placeholder="请选择" disabled>
              <el-option v-for="item in depVule[0].children" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="请假类别" prop="leaveType">
            <el-radio-group v-model="ruleForm.leaveType" disabled>
              <el-radio value="事假" name="type">
                事假
              </el-radio>
              <el-radio value="病假" name="type">
                病假
              </el-radio>
              <el-radio value="婚假" name="type">
                婚假
              </el-radio>
              <el-radio value="产假" name="type">
                产假
              </el-radio>
              <el-radio value="丧假" name="type">
                丧假
              </el-radio>
              <el-radio value="补休" name="type">
                补休
              </el-radio>
              <el-radio value="工伤" name="type">
                工伤
              </el-radio>
              <el-radio value="其他" name="type">
                其他
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="请假时间" style="height: 90px; width: 600px;">
            <el-date-picker v-model="dateRange" type="datetimerange" range-separator="至" start-placeholder="开始时间"
              end-placeholder="结束时间" @change="GetDateVule" style=" width: 600px;" disabled />
            <!-- 动态显示计算出的天数和小时数 -->
            <p style=" width: 600px;">
              共 {{ totalDays }} 天 {{ remainingHours.toString().padStart(2, '0') }} 小时
            </p>
            <p style=" width: 600px;">
              报道时间: {{ dateRange[1] ? moment(dateRange[1]).format("yyyy-MM-DD HH:mm:ss") : "未选择" }}
            </p>
          </el-form-item>
          <el-form-item label="请假事由">
            <el-input v-model="ruleForm.leaveReason" type="textarea" show-word-limit maxlength="140" disabled />
          </el-form-item>
          <el-form-item label="审核" v-show="store.ccstore.userId != route.query.userId" prop="recordStatus">
            <el-radio-group v-model="RecordForm.recordStatus" :disabled="IsStatus">
              <el-radio value="通过" name="type">
                通过
              </el-radio>
              <el-radio value="不通过" name="type">
                不通过
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="RecordForm.recordStatus == '不通过'" label="原因" prop="reason">
            <el-input v-model="RecordForm.reason" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              提交
            </el-button>
            <el-button type="primary" @click="FanHui()">
              返回
            </el-button>
          </el-form-item>
        </el-form>
      </el-aside>
      <el-aside width="300px">
        <el-table :data="tableData" border style="width: 100%;" v-show="store.ccstore.userId != route.query.userId">
          <el-table-column prop="approveNickName" label="审批人" />
          <el-table-column prop="recordStatus" label="审批结果" width="">
            <template v-slot="scoped">
              {{ scoped.row.recordStatus ? scoped.row.recordStatus : "未审批" }}
            </template>
          </el-table-column>
          <el-table-column prop="reason" label="原因" width="">
            <template v-slot="scoped">
              {{ scoped.row.reason ? scoped.row.reason : "无" }}
            </template>
          </el-table-column>
        </el-table>
      </el-aside>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus';
import moment from 'moment';
import { compile, computed, onMounted, reactive, ref } from 'vue'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { useRouter, useRoute } from 'vue-router';
import { useCounterStore } from '@/stores/counter';
import DepData from '@/stores/departmentData'
import axios from 'axios';

//部门信息
const depVule = DepData;
//pini保存
const store = useCounterStore();
//跳转
const router = useRouter();
//传参
const route = useRoute();
//审批状态 是否已审批 false未审批 true已审批
const IsStatus = ref(false)


//#region 请假申请表单添加


//返回按钮
const FanHui = () => {
  router.push("/ListLeaveModel")
}

//#region 反填

//处理反填的数据
const FanTianData = () => {
  //反填时间范围
  if (route.query.leavePeriod) {
    const [Adate, Bdate] = route.query.leavePeriod.split('至');
    console.log([Adate, Bdate], "字符串转换时间")
    const Adates = moment(Adate).toDate();
    const Bdates = moment(Bdate).toDate();
    //时间参数
    dateRange.value = [Adates, Bdates]
    // console.log(dateRange.value, "时间参数")
    GetDateVule(dateRange.value);
    //反填审批结果
    FanTianStatus()
  }


}

//反填审批结果
const FanTianStatus = () => {
  //反填审批结果 (通过 -- 不通过)
  axios.get(`https://localhost:7174/api/Approve/FanTianAPPlicant?LeaveId=${route.query.leaveId}&UserId=${store.ccstore.userId}`).then(res => {
    RecordForm.recordStatus = res.data.data.recordStatus
    RecordForm.reason = res.data.data.recordStatus
    console.log(RecordForm.recordStatus, "反填状态")
    console.log(RecordForm.reason, "反填拒绝原因")
    //状态 1未审批 2已审批
    if (RecordForm.recordStatus) {
      //修改为已审批
      IsStatus.value = true
      console.log(IsStatus.value, "修改为已审批")
    }
    if (!RecordForm.recordStatus) {
      //修改为未审批
      IsStatus.value = false
    }

  })
}


//#endregion


//#region  时间计算


//定义一个响应式变量来存储日期范围
const dateRange = ref([])
// 定义响应式变量来存储总天数
const totalDays = ref(0);
// 定义响应式变量来存储剩余小时数
const remainingHours = ref(0);


//计算某一天的请假时长
const calculateDailyHours = (date: Date, start: Date, end: Date) => {
  console.log("calculateDailyHours方法执行")
  let dailyHours = 0;
  const morningStart = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 8, 0, 0);
  const morningEnd = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 12, 0, 0);
  const afternoonStart = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 14, 0, 0);
  const afternoonEnd = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 18, 0, 0);

  // 计算上午的请假时长
  if (start < morningEnd && end > morningStart) {
    const overlapStart = Math.max(start, morningStart);
    const overlapEnd = Math.min(end, morningEnd);
    dailyHours += (overlapEnd - overlapStart) / (1000 * 60 * 60);
  }

  // 计算下午的请假时长
  if (start < afternoonEnd && end > afternoonStart) {
    const overlapStart = Math.max(start, afternoonStart);
    const overlapEnd = Math.min(end, afternoonEnd);
    dailyHours += (overlapEnd - overlapStart) / (1000 * 60 * 60);
  }

  return dailyHours;
};

//处理日期选择变化的函数
const GetDateVule = (date: any) => {
  console.log("GetDateVule方法执行")

  if (date.length === 2) {
    const startDate = date[0];
    const endDate = date[1];
    let totalHours = 0;

    // 遍历日期范围，计算每天的请假时长
    let currentDate = new Date(startDate);
    while (currentDate <= endDate) {
      totalHours += calculateDailyHours(currentDate, startDate, endDate);
      currentDate.setDate(currentDate.getDate() + 1);
    }

    // 计算总天数
    totalDays.value = Math.floor(totalHours / 8);
    // 计算剩余小时数
    remainingHours.value = parseFloat((totalHours % 8).toFixed(1));
    //总小时
    ruleForm.leaveTime = totalDays.value * 8 + remainingHours.value;
  }
  //总 开始时间 至 结束时间
  ruleForm.leavePeriod = (moment(date[0]).format("yyyy-MM-DD HH:mm:ss") + " 至 " + moment(date[1]).format("yyyy-MM-DD HH:mm:ss")).toString();
  //报道时间
  // ruleForm.leaveEndTime = moment(date[1]).format("yyyy-MM-DD HH:mm:ss");
  ruleForm.leaveEndTime = date[1];
  //报道时间 修改为当前北京时间
  // ruleForm.leaveEndTime = moment().utcOffset(8).toISOString(); // 修改部分
  // console.log("开始时间", date[0])
  // console.log("结束时间", date[1])
}

//#endregion


//#region 显示审核结果
const tableData = ref([])

const GetAppName = () => {
  axios.get(`https://localhost:7174/api/Approve/GetLeaveRecord?LeaveId=${route.query.leaveId}&DepId=${route.query.depId}&LevelRoleId=${store.ccstore.levelRoleId}`).then(res => {
    tableData.value = res.data.data
  })
}

//#endregion

//#region  对象

const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
//添加数据
const ruleForm = reactive({
  "nickName": route.query.nickName, //ok
  "depId": route.query.depId, //ok
  "leaveType": route.query.leaveType,
  "leavePeriod": route.query.leavePeriod, //请假时间 至  ok
  "leaveTime": route.query.leaveTime,     //总工时 ok
  "leaveEndTime": route.query.leaveEndTime, //报道时间 ok
  "leaveReason": route.query.leaveReason,  //事由 ok
  "leaveLeader": "",  //部门领导
  "appStatus": 1,     //状态 ok
  "createTime": route.query.createTime,//创建时间 ok 
  "levelRoleId": route.query.levelRoleId,   //审核等级
  "userId": route.query.userId,
  "leaveId": route.query.leaveId,
})


//传过去的数据
const RecordForm = reactive<RuleForm>({
  "leaveId": route.query.leaveId, //请假申请表id
  "depId": route.query.depId,                     //部门id
  "userId": store.ccstore.userId,                    //审核人id
  "approveNickName": store.ccstore.nickName,    //审核人名称
  "recordStatus": "",                 //审核结果 (通过,不通过)
  "levelRoleId": route.query.levelRoleId,               //审批层级
  "createTime": new Date(), //创建时间
  "reason": ""              //意见(通过可空 , 不通过必填)
})

//验证
const rules = reactive<FormRules<RuleForm>>({
  reason: [
    { required: true, message: '请输入原因', trigger: 'blur' },
  ],
  recordStatus: [
    { required: true, message: '请输选择', trigger: 'blur' },
  ],
});


//反填 审批状态






//审批
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    //已审批,不可再次审批
    if (IsStatus.value == true) {
      ElMessage.error("已审批,不可再次审批")
      return
    }

    if (valid) {
      axios.post("https://localhost:7272/api/Approve/AddLeaveRecordModel", RecordForm).then(res => {
        if (res.data.code == 218) {
          ElMessage.success(res.data.msg)
          router.push("/ListLeaveModel")
        } else {
          ElMessage.error(res.data.msg)
          router.push("/ListLeaveModel")
        }
      })
    } else {
      // console.log('error submit!', fields)
    }
  })
}

//#endregion



onMounted(() => {
  //时间反填
  FanTianData()
  //显示审批人及结果
  GetAppName()
  console.log(route.query, "传来的修改数据")
})


</script>

<style scoped></style>